package com.diligent.cloud.sfc.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.model.Result;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.diligent.cloud.sfc.model.MfgConsume;
import com.diligent.cloud.sfc.model.OrderType;
import com.diligent.cloud.sfc.model.info.ColorInfo;
import com.diligent.cloud.sfc.model.info.LotsFilterInfo;
import com.diligent.cloud.sfc.model.info.PowderBoxInfo;
import com.diligent.cloud.sfc.model.info.inventory.FeedPowderInventoryInfo;
import com.diligent.cloud.sfc.model.params.PowderBoxParams;
import com.diligent.cloud.sfc.service.ISfcService;
import com.diligent.cloud.sfc.service.WorkshopSceneSprayingProcessService;
import com.diligent.cloud.upc.feign.service.UpcInBoxServiceFeign;
import com.diligent.cloud.upc.model.UpcMessage;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.workorder.model.WoLots;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.service.WoLotsFeignService;
import com.diligent.cloud.workorder.service.WoOrderFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgConsumeMasterFeignService;
import com.diligent.cloud.workordermd.model.MfgConsumeDetail;
import com.diligent.cloud.workordermd.model.MfgConsumeMaster;
import com.diligent.foundation.data.model.v2.Condition;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.*;

/**
 * WorkshopSceneSprayingProcessServiceImpl class
 *
 * @author xf107278
 * @date 4/17/2020
 */
@Service
public class WorkshopSceneSprayingProcessServiceImpl implements WorkshopSceneSprayingProcessService {

    private MfgConsumeMasterFeignService mfgConsumeMasterFeignService;


    private ISfcService sfcBaseService;

    private WoLotsFeignService lotsFeignService;

    private WoOrderFeignService orderFeignService;

    private final UpcInBoxServiceFeign upcInBoxServiceFeign;


    public WorkshopSceneSprayingProcessServiceImpl(MfgConsumeMasterFeignService mfgConsumeMasterFeignService,
                                                   ISfcService sfcBaseService, WoLotsFeignService lotsFeignService,
                                                   WoOrderFeignService orderFeignService,
                                                   UpcInBoxServiceFeign upcInBoxServiceFeign) {
        this.mfgConsumeMasterFeignService = mfgConsumeMasterFeignService;
        this.sfcBaseService = sfcBaseService;
        this.lotsFeignService = lotsFeignService;
        this.orderFeignService = orderFeignService;
        this.upcInBoxServiceFeign = upcInBoxServiceFeign;
    }

    /**
     * 上粉接口
     *
     * @param powderBoxParams
     * @param backPowder
     * @param principal
     * @return
     */
    @Override
    public Result addPowderInventory(PowderBoxParams powderBoxParams, Boolean backPowder, Principal principal) {
        PowderBoxInfo powderBoxInfo = new PowderBoxInfo();

        Set<String> scanningColorSystem = new HashSet<>();
        MfgConsumeMaster consumeMaster;
        MfgConsumeDetail consumeDetail ;

        for (FeedPowderInventoryInfo feedPowderInfo : powderBoxParams.getFeedPowderInfos()) {
            scanningColorSystem.add(feedPowderInfo.getMatCode());

            MfgConsume mfgConsume = sfcBaseService.addMatInventoryInfo(feedPowderInfo
                    , sfcBaseService.addMatConsumerInventory(powderBoxParams, principal));

            consumeMaster = mfgConsume.getMfgConsumeMaster();
            consumeDetail = mfgConsume.getMfgConsumeDetail();

            consumeMaster.setWeight(feedPowderInfo.getWight());
            consumeDetail.setBarcode(feedPowderInfo.getBarcode());
            consumeDetail.setWeight(feedPowderInfo.getWight());
            if (backPowder) {
                consumeDetail.setReturnWeight(feedPowderInfo.getWight());
                consumeMaster.setReturnWeight(feedPowderInfo.getWight());
            }
            com.diligent.cloud.workordermd.model.MfgConsume consume =
                    new com.diligent.cloud.workordermd.model.MfgConsume();
            BeanUtils.copyProperties(mfgConsume,consume);

            mfgConsumeMasterFeignService.add(consume);

        }
        powderBoxInfo.setFeedPowderDetail(powderBoxParams.getFeedPowderInfos());
        powderBoxInfo.setScanningColorSystem(scanningColorSystem.size());
        powderBoxInfo.setScanningPowderBox(powderBoxParams.getFeedPowderInfos().size());
        if (backPowder) {
            ObjectResult result = new ObjectResult();
            result.modifyCode(Codes.success.getCode(), "退粉成功");
            return result;
        } else {
            UpcMessage upcMessage = new UpcMessage();
            List<Long> longList = new ArrayList<>();
            longList.add(1L);
            upcMessage.setTerminalRegistryIds(longList);
            upcMessage.setHead("2");
            String message = "{\"methodname\":\"GetPowderBox\",\"appname\":\"Foreground\"," +
                    "\"activity\":\"UpperPowdermain_Activity\"}";
            JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
            jsonObject.put("feedPowderInfos", powderBoxParams.getFeedPowderInfos());
            upcMessage.setContent(jsonObject.toJSONString());
            upcInBoxServiceFeign.message(upcMessage);
        }
        return new ObjectResult<>(powderBoxInfo);
    }

    @Override
    public ListResult<ColorInfo> getColorList(String machCode, String matCode) {
        return sfcBaseService.getMatList(machCode, OrderType.表面处理工单, matCode);
    }

    @Override
    public ResponseEntity<ListResult> getLotsFilter(String woOrder, Long systemId) {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> byWoOrder =
                orderFeignService.getByWoOrder(woOrder, systemId);
        Preconditions.checkNotNull(byWoOrder.getBody(),"查询不到此[%s]工单",woOrder);

        List<Map> woOrders1 = (List<Map>)byWoOrder.getBody().getData();
        WoOrder woOrder1 =
                JSON.toJavaObject(JSON.parseObject(JSONObject.toJSONString(woOrders1.stream().findFirst().get())),
                        WoOrder.class);
        //喷涂单胚料BatchCode
        String batchCode = woOrder1.getBatchCode();
        //喷涂单胚料型号
        String matCode = woOrder1.getMatCode();

        PageAndCondition pageAndCondition = new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        Condition condition = new Condition("batchCode", "eq", batchCode, null);
        Condition condition1 = new Condition("matCode", "eq", matCode, null);
        Condition condition2 = new Condition("orderType", "eq", OrderType.挤压工单, null);
        conditions.add(condition);
        conditions.add(condition1);
        conditions.add(condition2);
        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(new Pagination(1L, 1L));

        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOrder>>> orderPage =
                orderFeignService.page(pageAndCondition);
        if (orderPage.getBody()==null){return ResponseEntity.ok(new ListResult(new ArrayList())); }
        List<WoOrder> woOrders = orderPage.getBody().getData().getRecords();
        List<LotsFilterInfo> lotsFilterInfos = new ArrayList<>();
        for (WoOrder order : woOrders) {
            PageAndCondition pageAndCondition1 = new PageAndCondition();
            List<Condition> conditions1 = new ArrayList<>();
            pageAndCondition1.setPagination(new Pagination(1L, 100000L));
            conditions1.add(new Condition("woOrder", "eq", order.getWoOrder(), null));
            conditions1.add(new Condition("isCanceled", "eq", 0, null));
            pageAndCondition1.setConditions(conditions1);
            ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoLots>>> page =
                    lotsFeignService.page(pageAndCondition1);
            if (page.getBody()!=null && page.getBody().getData().getRecords().size() != 0) {
                LotsFilterInfo lotsFilterInfo;
                for (WoLots woLots : page.getBody().getData().getRecords()) {
                    lotsFilterInfo = new LotsFilterInfo();
                    lotsFilterInfo.setColor(order.getColorGroupCode());
                    lotsFilterInfo.setDigit(order.getDeliveryDigit().intValue());
                    lotsFilterInfo.setMatCode(order.getMatCode());
                    lotsFilterInfo.setLotCode(woLots.getLotCode());
                    lotsFilterInfo.setWoOrder(order.getWoOrder());
                    lotsFilterInfos.add(lotsFilterInfo);
                }
            }
            return ResponseEntity.ok(new ListResult(lotsFilterInfos));
        }
        return ResponseEntity.ok(new ListResult(new ArrayList()));
    }

    @Override
    public ResponseEntity<ObjectResult<WoLots>> getLotsInfo(String lotCode) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        pageAndCondition.setConditions(Collections.singletonList(new Condition("lotCode", "eq", lotCode, null)));
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoLots>>> page =
                lotsFeignService.page(pageAndCondition);

        ObjectResult result = new ObjectResult(page.getBody().getData().getRecords().stream().findFirst().get());
        result.modifyCode(page.getBody().getCode(), page.getBody().getMsg());
        return ResponseEntity.ok(result);
    }

    @Override
    public ResponseEntity<ObjectResult<WoLots>> getBoxByLots(String lotCode) {
//        PageAndCondition pageAndCondition = new PageAndCondition();
//        pageAndCondition.setPagination(new Pagination(1L, 1L));
//        pageAndCondition.setConditions(Collections.singletonList(new Condition("lotCode", "eq", lotCode, null)));
//        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoLots>>> page =
//                lotsFeignService.page(pageAndCondition);
//       WoLots woLots =  page.getBody().getData().getRecords().stream().findFirst().get();
        return null;
    }


}
